package com.gxuwz.medical.web.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

import com.gxuwz.medical.dao.MemberDao;
import com.gxuwz.medical.dao.PayRecordDao;
import com.gxuwz.medical.domain.house.House;
import com.gxuwz.medical.domain.member.Member;
import com.gxuwz.medical.domain.payRecord.PayRecord;
import com.gxuwz.medical.domain.payStandard.PayStandard;
import com.gxuwz.medical.exception.DbException;

public class PayRecordServlet extends BaseServlet  {

	private static final long serialVersionUID = 1L;


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			this.doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String m = request.getParameter("m");
		if("list".equals(m)){
			process(request,response,"/page/payRecord/payRecord_list.jsp");
		}else if("check".equals(m)){
			check(request,response);
		}else if("statistics".equals(m)){
			process(request, response, "/page/payRecord/payRecord_statistics.jsp");
		}else if("detail".equals(m)){
			process(request, response, "/page/payRecord/payRecord_add.jsp");
		}else if("calAccount".equals(m)){
			calAccount(request, response);
		}else if("add".equals(m)){
			add(request,response);
		}else if("del".equals(m)){
			del(request,response);
		}else if("Excel".equals(m)){
			createExcel(request, response);
		}else if("select".equals(m)){
			select(request, response);
		}else if("iscanhe".equals(m)){
			try {
				iscanhe(request,response);
			} catch (DbException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}else if("listapply".equals(m)){
			process(request, response,"/page/chronicdisApply/chronicdisApply_list.jsp");
		}else {
			error(request, response);
		}
	}
	
	
	private void check(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		try {
			boolean flag = false;
			// 获取系统当前年度以及当前时间
			Calendar date = Calendar.getInstance();
			String thisYear = String.valueOf(date.get(Calendar.YEAR));
			Date payTime = date.getTime();
			// 获取当前年度的缴费标准规定时间范围
			PayStandard prd = new PayStandard(thisYear);
			
			// 设置当前时间
	        date.setTime(payTime);
	        // 设置缴费开始时间
	        Calendar begin = Calendar.getInstance();
	        begin.setTime(prd.getStartTime());
	        // 设置缴费结束时间
	        Calendar end = Calendar.getInstance();
	        end.setTime(prd.getEndTime());
	        
	        // 判断当前时间是否等于缴费标准规定时间
	        if(payTime == prd.getStartTime() || payTime == prd.getEndTime()) {
				flag = true;
			}
	        // 判断当前时间是否在缴费标准规定时间范围内
	        if (date.after(begin) && date.before(end)) {
	            flag = true;
	        } 
			if(flag) {
				response.getWriter().write("true");
			}else {
				response.getWriter().write("false");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	 // 计算缴费总金额
	private void calAccount(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException{
		// 1:接收表单传过来的缴费人数
		int payNum = Integer.parseInt(req.getParameter("payNum"));
		try {
			// 2:获取当前年度的缴费标准金额
			Calendar date = Calendar.getInstance();
			String thisYear = String.valueOf(date.get(Calendar.YEAR));
			PayStandard psd = new PayStandard(thisYear);
			double account = psd.getAccount();
			// 3:执行计算方法
			PayRecordDao prd = new PayRecordDao();
			double amount = prd.calAccount(payNum, account);
			// 4:将计算得到的缴费总金额返回给页面
			response.getWriter().write(""+amount);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	 // 添加参合缴费记录
	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// 1:接收表单传过来的值
				String familycode = request.getParameter("familycode");
			//	System.out.println("familycode:"+familycode);
				String housemaster = request.getParameter("housemaster");
			//	System.out.println("housemaster:"+housemaster);
				// 个人户内编号数组
				String[] housecode = request.getParameterValues("ids");
			//	System.out.println("housecode:"+housecode);
				// 参合发票号
				String chzNumber = request.getParameter("chzNumber");
			//	System.out.println("chzNumber:"+chzNumber);
				try {
					// 家庭缴费总金额
					double amount = Double.parseDouble(request.getParameter("payAmount"));
			//		System.out.println("amount:"+amount);
					// 单个人缴费金额
					double payAmount = (amount / housecode.length);
			//		System.out.println("payAmount:"+payAmount);
					// 2:获取系统当前年度以及当前时间
					Calendar date = Calendar.getInstance();
					String payYear = String.valueOf(date.get(Calendar.YEAR));
			//		System.out.println("payYear:"+payYear);
					Date payTime = date.getTime();
			//		System.out.println("payTime:"+payTime);
					// 3:获取当前用户作为操作员
					String register=(String)request.getSession().getAttribute("userName");
					// 遍历个人户内编号，循环执行预添加方法
					for(int i = 0; i < housecode.length; i++) {
						// 4:根据个人户内编号获取个人姓名
						Member model = new Member(housecode[i]);
						String name = model.getName();
			//			System.out.println("name:"+name);

						// 5:将参合证号设为个人户内编号
						String chzcode = housecode[i];
			//			System.out.println("chzcode:"+chzcode);
						PayRecord prd = new PayRecord(chzNumber,chzcode,name,familycode,housemaster,housecode[i],
								payYear,payAmount,payTime,register);
						// 调用预添加方法
						prd.AddPayRecord();
					}
				}catch (Exception e) {
					e.printStackTrace();
				}	
	}
	
	
	 
	  //删除家庭缴费记录
	 private void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// 接收表单传过来的数据
		String familycode = request.getParameter("familycode");
		System.out.println("familycode:"+familycode);
		try {
			PayRecord prd = new PayRecord();
			prd.setFamilycode(familycode);
			boolean flag = prd.DeletePayRecord();
			if(flag) {
				response.getWriter().write("true");
			}else {
				response.getWriter().write("false");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	 
	
	  // 导出Excel
	 private void createExcel(HttpServletRequest req, HttpServletResponse response) {
		 
		PayRecordDao dao = new PayRecordDao();
		String sql = "select * from t_payRecord  where 1=1";
		Object[] params = {};
		List<PayRecord> list = new ArrayList<PayRecord>();
		// 家庭总人口数
		int personCount = 0;
		// 家庭当前年度已缴费人数
		int payCount = 0;
		// 缴费总金额
		double amount = 0;
		try {
			list = dao.queryOjects(sql, params);
			
			MemberDao memberDao = new MemberDao();
			for(int i = 0; i< list.size(); i++) {
				
				PayRecord model = list.get(i);
				personCount = memberDao.getMemberSizeById(model.getFamilycode());
				// 获取家庭当前年度已缴费人数
				payCount =  dao.getByFamily(model.getFamilycode(), model.getPayYear());
				// 获取当前年度的缴费标准金额
				PayStandard psd = new PayStandard(model.getPayYear());
				double account = psd.getAccount();
				amount = dao.calAccount(payCount, account);
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		 
        // 创建一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个工作表
        HSSFSheet sheet = workbook.createSheet("家庭参合缴费统计");
        
        CellRangeAddress region = new CellRangeAddress(0, // first row
                0, // last row
                0, // first column
                9 // last column
        );
        sheet.addMergedRegion(region);
        
        HSSFRow hssfRow = sheet.createRow(0);
        HSSFCell headCell = hssfRow.createCell(0);
        headCell.setCellValue("家庭参合缴费统计信息");
        
        // 设置单元格格式居中
        HSSFCellStyle cellStyle = workbook.createCellStyle();
    	cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headCell.setCellStyle(cellStyle);
        
        
        // 添加表头行
        hssfRow = sheet.createRow(1);
        // 添加表头内容
        headCell = hssfRow.createCell(0);
        headCell.setCellValue("家庭编号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(1);
        headCell.setCellValue("户主");
        headCell.setCellStyle(cellStyle);
        
        headCell = hssfRow.createCell(2);
        headCell.setCellValue("姓名");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(3);
        headCell.setCellValue("家庭人口数");
        headCell.setCellStyle(cellStyle);
        
        
        headCell = hssfRow.createCell(4);
        headCell.setCellValue("已缴费人数");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(5);
        headCell.setCellValue("缴费总金额");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(6);
        headCell.setCellValue("参合发票号");
        headCell.setCellStyle(cellStyle);
        
        headCell = hssfRow.createCell(7);
        headCell.setCellValue("缴费年度");
        headCell.setCellStyle(cellStyle);
        
        headCell = hssfRow.createCell(8);
        headCell.setCellValue("缴费时间");
        headCell.setCellStyle(cellStyle);
        
        headCell = hssfRow.createCell(9);
        headCell.setCellValue("操作员");
        headCell.setCellStyle(cellStyle);

        // 添加数据内容
        for (int i = 0; i < list.size(); i++) {
            hssfRow = sheet.createRow((int) i + 2);
            PayRecord  model = list.get(i);

            // 获取缴费的日期
            Date date = model.getPayTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //转换成String类型的时间
            String payTime = sdf.format(date);
            
            // 创建单元格，并设置值
            HSSFCell cell = hssfRow.createCell(0);
            cell.setCellValue(model.getFamilycode());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(1);
            cell.setCellValue(model.getHousemaster());
            cell.setCellStyle(cellStyle);
            
            cell = hssfRow.createCell(2);
            cell.setCellValue(model.getName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(3);
            cell.setCellValue(personCount);
            cell.setCellStyle(cellStyle);
            
            cell = hssfRow.createCell(4);
            cell.setCellValue(payCount);
            cell.setCellStyle(cellStyle);
            
            cell = hssfRow.createCell(5);
            cell.setCellValue(amount);
            cell.setCellStyle(cellStyle);
            
            cell = hssfRow.createCell(6);
            cell.setCellValue(model.getChzNumber());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(7);
            cell.setCellValue(model.getPayYear());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(8);
            cell.setCellValue(payTime);
            cell.setCellStyle(cellStyle);
            
            cell = hssfRow.createCell(9);
            cell.setCellValue(model.getRegister());
            cell.setCellStyle(cellStyle);
            
        }
        // 保存Excel文件
        try {
        	response.setContentType("application/vnd.ms-excel");
        	response.setHeader("Content-disposition", "attachment;filename=payRecord.xls");//附件形式下载，文件名叫payRecord.xls
        	//OutputStream outputStream = new FileOutputStream("D:/payRecord.xls");//保存到本地（服务器端）
        	OutputStream outputStream = response.getOutputStream();	 //写到客户端       	
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	 
	 protected void select(HttpServletRequest request,
				HttpServletResponse response) throws ServletException, IOException {
			try {
				// 定义一个sb来接收模糊查询的sql
				StringBuffer sb = new StringBuffer(1024);
				// form表单提交过来的用户输入的title模糊查询关键字
				String housemaster = request.getParameter("title");
				// System.out.println("housemaster:" + housemaster);
				
				// 如果housemaster有输入的时候，才拼接sql进行查询
				 if (housemaster != null && !"".equals(housemaster)) {
					sb.append(" housemaster like '%" + housemaster + "%'");
				}

				List<House> newsList = House.getNewsList(sb.toString());

				request.setAttribute("newsList", newsList);
				request.getRequestDispatcher("/page/member/member_open.jsp")
						.forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	 
	 private void iscanhe(HttpServletRequest request, HttpServletResponse response) throws DbException, IOException, SQLException{
		 // 解决json中文乱码
	    response.setContentType("text/json;charset=UTF-8");
	    response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String idcard = request.getParameter("mhcx");
	//	System.out.println("idcard："+idcard);
		
		Member member = new Member();
		member.loadDByIdcard(idcard);
		String housecode = member.getHousecode();
	//	System.out.println("housecode:"+housecode);
		
		PayRecordDao payRecordDao = new PayRecordDao();
		boolean  iscanhe = payRecordDao.isCanHe(housecode);
	//	System.out.println("iscanhe:"+iscanhe);
		Gson gson = new Gson();
	    String json = gson.toJson(iscanhe);
	    out.println(json);
	    out.flush();
	    out.close();

	}
	 
	 
}
